package com.zmn.oms.third.core;

import com.zmn.oms.common.enums.ChannelFacade;
import com.zmn.oms.manager.utils.SpringBeanFactoryUtil;
import com.zmn.oms.model.entity.chan.FacadeMessageEvent;
import com.zmn.oms.third.core.interfaces.FacadeMessageEventHandler;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 类描述：
 *
 * @author lhl
 * @date 2020/12/30 0:00
 */
public final class FacadeMessageEventHandlerFactory {

    private static final Map<String, FacadeMessageEventHandler> handerCache = new HashMap<>();

    public static FacadeMessageEventHandler getInstance(FacadeMessageEvent facadeMessageEvent) {
        String handlerName = Optional.ofNullable(facadeMessageEvent)
                .map(FacadeMessageEvent::getFacadeId)
                .map(ChannelFacade::getByFacadeId)
                .map(ChannelFacade::getFacadeMessageEventHandler)
                .orElse(null);

        if (handlerName == null) {
            return null;
        }

        FacadeMessageEventHandler handler = handerCache.get(handlerName);

        if (handler == null) {
            Object bean = SpringBeanFactoryUtil.getBean(handlerName);
            if (bean != null && bean instanceof FacadeMessageEventHandler) {
                handler = (FacadeMessageEventHandler)bean;
                handerCache.put(handlerName, handler);
            }
        }

        return handler;
    }

    /**
     * 私有构造器，禁止外部实例化
     */
    private FacadeMessageEventHandlerFactory() {}
}
